﻿using B.S.ProductionProject.Domain;
using B.S.ProductionProject.ErrorCode;
using B.S.ProductionProject.Write.WebAPI.Applications.Commands.ProductionScheduleDetailCommand;
using MediatR;
using SqlSugar;

namespace B.S.ProductionProject.Write.WebAPI.Applications.CommandHandlers.ProductionScheduleDetailCommandHandler
{
    public class DelProductionScheduleDetailCommandHandler : IRequestHandler<DelProductionScheduleDetailCommand, APIResult<object>>
    {
        private readonly ISqlSugarClient db;

        public DelProductionScheduleDetailCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<object>> Handle(DelProductionScheduleDetailCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.code = APIResultCode.success;
            result.msg = "删除成功";
            var ids = request.ProductionScheduleDetailIds.Split(',').Select(int.Parse).ToList();

            // 一次性查询所有要删除的记录
            var itemsToDelete = await db.Queryable<ProductionScheduleDetail>().Where(p => ids.Contains(p.ProductionScheduleDetailId)).ToListAsync();

            foreach (var item in itemsToDelete)
            {
                item.isDelete = true;
                await db.Updateable(item).ExecuteCommandAsync();
            }

            return result;
        }
    }
}
